using System;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sedna.Core.Controller.Configurations;
using Sedna.Core.Controls.Support;
using Sedna.Core.Globalization;
using Spring.Util;
using ControlBuilder=Sedna.Core.Controls.Support.ControlBuilder;

namespace Sedna.Core.Controls.Template
{
	public class HeaderColumnTemplate : ITemplate
	{
		private DataGrid dataGrid;
		private IDataGridColumnConfiguration columnConfiguration;

		public HeaderColumnTemplate(DataGrid dataGrid, IDataGridColumnConfiguration columnConfiguration)
		{
			this.dataGrid = dataGrid;
			this.columnConfiguration = columnConfiguration;
		}

		public void InstantiateIn(Control container)
		{
			Control control = GetControlInstance();

			SetCommonProperties(control);

			if (columnConfiguration.Sortable)
			{
				SetSortProperties(control);
			}

			container.Controls.Add(GetHeaderControlInstance(control));
            if (HttpContext.Current.Request.Browser.Browser == "Firefox")
            {
                ((WebControl)container).CssClass = "innertableheaderMOZ";
            }
            else
            {
                ((WebControl)container).CssClass = "innertableheader";
            }
		}

		#region Private Members

		private Control GetControlInstance()
		{
			if (columnConfiguration.HeaderControlConfiguration != null)
			{
				Control control = ControlBuilder.BuildControl(columnConfiguration.HeaderControlConfiguration);
				return control;
			}
			else
			{
				if (columnConfiguration.Sortable)
				{
					System.Web.UI.WebControls.LinkButton linkButton = new System.Web.UI.WebControls.LinkButton();
					linkButton.Style.Add("font-weight", "bold");
					//should not cause validation, when sorting changes
					//maybe take value from columnConfiguration.CausesValidation?
					linkButton.CausesValidation = false;
					return linkButton;
				}
				else
				{
					System.Web.UI.WebControls.Label label = new System.Web.UI.WebControls.Label();
					label.Style.Add("font-weight", "bold");
					
					return label;
				}
			}
		}

		private HeaderControl GetHeaderControlInstance(Control control)
		{
			if (IsSortMarkerVisible())
			{
				return new HeaderControl(control, dataGrid.Controller.CurrentDataProvider.IsAsc);
			}

			return new HeaderControl(control);
		}

		private bool IsSortMarkerVisible()
		{
            return (columnConfiguration != null && columnConfiguration.Sortable &&
				columnConfiguration.DisplaySortMarker && 
                dataGrid.Controller != null &&
                dataGrid.Controller.CurrentDataProvider != null &&
                columnConfiguration.SortExpression != null &&
                columnConfiguration.SortExpression.Equals(dataGrid.Controller.CurrentDataProvider.SortExpression));
		}

		private void SetCommonProperties(Control control)
		{
			SetProperty(control, "Text", columnConfiguration.GetLocalizedPostfixLabel(columnConfiguration.TextKey));
			SetProperty(control, "Enabled", columnConfiguration.IsEnabledForPrincipal());
		}

		private void SetSortProperties(Control control)
		{
			SetProperty(control, "CommandName", System.Web.UI.WebControls.DataGrid.SortCommandName);
			SetProperty(control, "CommandArgument", columnConfiguration.SortExpression);					
		}

		private void SetProperty(Control control, String propertyName, Object value)
		{
			if (control != null && !StringUtils.IsNullOrEmpty(propertyName))
			{
				PropertyInfo propertyInfo = control.GetType().GetProperty(propertyName);

				if (propertyInfo != null)
				{
					propertyInfo.SetValue(control, value, null);
				}
			}
		}

	    
		#endregion

		#region HeaderControl class

		private class HeaderControl : Control, INamingContainer
		{
			private const String BLANK_GLYPH = "sort_blank.gif";
			private const String ASC_GLYPH = "sort_d.gif";
			private const String DESC_GLYPH = "sort_u.gif";

			private Control control;
			private String glyphName = BLANK_GLYPH;

			public HeaderControl(Control control)
			{
				this.control = control;				
			}

			public HeaderControl(Control control, bool isAsc)
			{
				this.control = control;
				this.glyphName = (isAsc ? ASC_GLYPH : DESC_GLYPH);			
			}

			protected override void OnInit(EventArgs e)
			{
				TableCell controlCell = new TableCell();				
				
				if (control != null)
				{					
					controlCell.Controls.Add(control);
					controlCell.Width = Unit.Percentage(100);
				}

				Table table = new Table();
				table.CellSpacing = 1;
				table.CellPadding = 0;
				table.BorderWidth = Unit.Pixel(0);
				table.Rows.Add(new TableRow());
				table.Rows[0].Cells.Add(controlCell);

				//if (!BLANK_GLYPH.Equals(glyphName))
				//{			    
					System.Web.UI.WebControls.Image glyph = new System.Web.UI.WebControls.Image();
					glyph.ImageUrl = ImageManager.Relate(glyph, glyphName);

					TableCell glyphCell = new TableCell();				
					glyphCell.HorizontalAlign = HorizontalAlign.Left;
					glyphCell.VerticalAlign = VerticalAlign.Middle;
					glyphCell.Controls.Add(glyph);
				
					table.Rows[0].Cells.Add(glyphCell);													    
				//}				

				Controls.Add(table);

				base.OnInit(e);
			}
		}

		#endregion
	}
}
